package com.feicheng.lanniao.controller.weChatNativePayV2;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.feicheng.lanniao.controller.weChatNativePay.constant.WechatPayConfig;
import com.feicheng.lanniao.entity.PayCost;
import com.feicheng.lanniao.entity.PayOrderv2;
import com.feicheng.lanniao.service.IPayCostService;
import com.feicheng.lanniao.service.IPayOrderv2Service;
import com.feicheng.lanniao.util.HttpUtils;
import com.feicheng.lanniao.util.QRCodeUtil;
import com.feicheng.lanniao.util.SnowflakeIdWorker;
import lombok.extern.slf4j.Slf4j;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author tianchunlei
 * @Des //微信支付扫码支付demo接口
 * @Date 2021/10/14
 **/
@RestController
@RequestMapping("/lanniao-user/pay")
@Slf4j
public class WechatNativeV2Controller {
	@Autowired
    IPayCostService iPayCostService;
      @GetMapping("/nativeV2")
      public byte[] pay(Integer clientId,String orderNumber,Integer orderTypeId,Integer money)throws Exception{
            log.info("================>获取支付二维码接口进入<==================");
            log.info("================>clientId="+clientId+"<==================");
            log.info("================>orderTypeId= "+orderTypeId+"<==================");
            log.info("================>money="+money+"<===================");
            log.info("================>orderNumber="+orderNumber+"<===================");
            /*
               封装请求参数
            */
            Map<String,Object> param = new HashMap<>();
            /*
               1.由微信生成的应用ID，全局唯一。请求基础下单接口时请注意APPID的应用属性，
                 例如公众号场景下，需使用应用属性为公众号的APPID
             */
            param.put("appid", WechatPayConfig.APPID);
            /*
               2.附加数据，在查询API和支付通知中原样返回，可作为自定义参数使用
             */
           JSONObject attch = new JSONObject();
           attch.put("clientId",clientId);
           attch.put("orderTypeId",orderTypeId);
           attch.put("money",money);
           log.info("================>attch:{}<================",attch);

          QueryWrapper<PayCost> wrapper = new QueryWrapper<PayCost>();
          wrapper.eq("order_type_id", orderTypeId);
          PayCost payCost = iPayCostService.getOne(wrapper);
           attch.put("description",payCost.getTypeName());
           param.put("attach", attch.toString()); //附加信息
            /*
               3.直连商户的商户号，由微信支付生成并下发 string[1,32]
             */
            param.put("mchid", WechatPayConfig.MCH_ID);
            /*
               4.商品描述 string[1,127]
             */

            param.put("description",payCost.getTypeName());
            log.info("description========>{}",payCost.getTypeName());
            /*
               5.商户系统内部订单号，只能是数字、大小写字母_-*且在同一个商户号下唯一
                  示例值：1217752501201407033233368018
                  这个地方要换成orderNumber
                  new SnowflakeIdWorker(1, 1).nextId() + ""
             */
            param.put("out_trade_no", orderNumber);
            /*
               6.通知URL必须为直接可访问的URL，不允许携带查询串，要求必须为https地址。
             */
            param.put("notify_url", WechatPayConfig.CALL_BACK);
            /*
               7.订单金额信息
             */
            Map<String, Object> amount = new HashMap();
            /*
              7.1 订单总金额，单位为分。示例值：100
              下面有一个方法，可以将元转换为分，按照实际业务需要来调用即可
             */
            amount.put("total", money);
            /*
              7.2 CNY：人民币，境内商户号仅支持人民币。示例值：CNY
             */
            amount.put("currency", "CNY");
            param.put("amount", amount);
            /*
            将要发送的所有参数解析为一个Json串,它代表是发送请求时的请求体
             */
            ObjectMapper objectMapper = new ObjectMapper();
            String body = objectMapper.writeValueAsString(param);
            log.info("================body= " + body);
            /*
             调用封装好的http客户端发送请求，同时接收报文
             */
            Map<String, Object> result = HttpUtils.doPost(WechatPayConfig.GATEWAY, body);
            log.info("================result=" + result);
            /*
              取出url
             */
            String codeUrl = result.get("code_url").toString();
            try {
                  ByteArrayOutputStream output = new ByteArrayOutputStream();
                  String logopath = null;
                  logopath = ResourceUtils.getFile(WechatPayConfig.LOGO).getAbsolutePath();
                  BufferedImage buff = QRCodeUtil.encode(codeUrl, logopath, false);
                  ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);
                  ImageIO.write(buff, "JPEG", imageOut);
                  imageOut.close();
                  ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());
                  return FileCopyUtils.copyToByteArray(input);
            }catch (Exception e){
                  e.printStackTrace();
            }
            //生成微信支付二维码
            return null;
      }

      /**
       * 元转换成分
       *
       * @param money
       * @return
       */
      private String getMoney(String money) {
            if (money == null || money.equalsIgnoreCase("0")) {
                  return "";
            }
            // 金额转化为分为单位
            // 处理包含, ￥ 或者$的金额
            String currency = money.replaceAll("\\$|\\￥|\\,", "");
            int index = currency.indexOf(".");
            int length = currency.length();
            Long amLong = 0L;
            if (index == -1) {
                  amLong = Long.valueOf(currency + "00");
            } else if (length - index >= 3) {
                  amLong = Long.valueOf((currency.substring(0, index + 3)).replace(".", ""));
            } else if (length - index == 2) {
                  amLong = Long.valueOf((currency.substring(0, index + 2)).replace(".", "") + 0);
            } else {
                  amLong = Long.valueOf((currency.substring(0, index + 1)).replace(".", "") + "00");
            }
            return amLong.toString();
      }
}
